import { ref, reactive, watch } from 'vue'
import { defineStore } from 'pinia'
import { useRouter } from 'vue-router'

export const useModuleStore = defineStore('module', () => {

  const currentView = ref('map')

  const router = useRouter()
  // 当前激活模块
  const currentModule = ref('cockpit')
  // 各模块对应的地图数据
  const mapData = reactive({
    cockpit: { entities: [], layers: [] },
    rescue: { entities: [], layers: [] },
    simulation: { entities: [], layers: [] },
    replay: { entities: [], layers: [] }
  })
  // 各模块对应的组件数据
  const componentData = reactive({
    cockpit: {},
    rescue: {},
    simulation: {},
    replay: {}
  })


  //
  const setCurrentView = (view) => {  // 添加这个 action
    currentView.value = view
  }
  // 监听路由变化更新模块
  watch(
    () => router.currentRoute.value.meta.module,
    (newModule) => {
      if (newModule) {
        currentModule.value = newModule
        loadModuleData(newModule) // 加载对应模块数据
      }
    },
    { immediate: true }
  )

  // 加载模块数据
  function loadModuleData(module) {
    // 实际项目中可替换为API请求
    switch (module) {
      case 'cockpit':
        mapData[module] = {
          entities: [{ id: 'cockpit-1', name: '基础监控点' }],
          layers: ['base-layer']
        }
        componentData[module] = { title: '全局监控数据' }
        break
      case 'rescue':
        mapData[module] = {
          entities: [{ id: 'rescue-1', name: '救援点' }],
          layers: ['rescue-layer']
        }
        componentData[module] = { title: '救援资源分布' }
        break
      // 其他模块类似...
    }
  }

  // 切换模块（供按钮点击调用）
  function switchModule(module) {
    currentModule.value = module
    // 根据模块查找对应路由并跳转
    const targetRoute = router.getRoutes().find(route => route.meta.module === module)
    if (targetRoute) {
      router.push(targetRoute.path)
    }
  }

  return { currentModule, mapData, componentData, switchModule }
})